package com.university.report.user.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.university.report.common.result.Result;
import com.university.report.common.result.ResultCodeEnum;
import com.university.report.model.entity.Permission;
import com.university.report.model.entity.Role;
import com.university.report.model.entity.RolePermission;
import com.university.report.model.entity.UserInfo;
import com.university.report.model.vo.PermissionRolesUserVo;
import com.university.report.model.vo.PermissionRolesVo;
import com.university.report.model.vo.UserInfoVO;
import com.university.report.user.mapper.PermissionMapper;
import com.university.report.user.service.IPermissionService;
import com.university.report.user.service.IRolePermissionService;
import com.university.report.user.service.IRoleService;
import com.university.report.user.service.UserAccountService;
import com.university.report.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jinondo
 * @since 2021-06-09
 */
@Api(tags = "用户信息控制器")
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    IPermissionService permissionService;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    IRolePermissionService rolePermissionService;

    @Autowired
    IRoleService roleService;



    @Autowired
    UserAccountService userAccountService;


    @ApiOperation(value = "查询当天未打卡的同学")
    @GetMapping("/getUnReported")
    public Result getUnreported(){
        List<UserInfo> unReported = userService.getUnReported();
        return Result.ok(unReported);
    }

    @ApiOperation(value = "导出当天未打卡名单")
    @GetMapping("/exportUnReported")
    public void exportUnReported(HttpServletResponse response){
        try {
            System.out.println("test");
           userService.exportUnReported(response);
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     *
     * @param id
     * @param username
     * @param reportStatus
     * @param currentPage  当前页数参数必须传
     * @return
     */
    @ApiOperation("根据用户id/用户名/打卡状态获取用户")
    @GetMapping("/getUserInfo")
    public Result<Object> getUserInfo(@RequestParam(value = "id",required = false) Integer id,
                                      @RequestParam(value = "username",required = false)String username,
                                      @RequestParam(value = "reportStatus",required = false)Integer reportStatus,
                                      @RequestParam(value = "currentPage")Integer currentPage)
    {

        Map<String, Object> map = userService.getUserInfoAtCondition(id, username, reportStatus, currentPage);
        if (!map.isEmpty())
        {
            return Result.ok(map);
        }
        return Result.fail(ResultCodeEnum.DATA_NOT_EXIST);
    }


    /*你这里export是指导出还是导入？*/
    @ApiOperation("导入用户信息")
    @RequestMapping(value = "/exportUser")
    public Result exportUser(@RequestBody MultipartFile file){
        System.out.println("aaaaaaaaa");
        userAccountService.importUserAccount(file);
        return Result.ok();
    }

    @ApiOperation("根据用户id查询用户信息")
    @GetMapping("/getUserInfoById")
    public Result getUserInfoById(@RequestParam("userId")Integer userId){
        UserInfoVO userInfoVOById = userService.getUserInfoVOById(userId);
        if (userInfoVOById==null){
            return Result.fail(ResultCodeEnum.DATA_NOT_EXIST);
        }
        return Result.ok(userInfoVOById);
    }

    @ApiOperation("更新用户信息")
    @PostMapping("/update")
    public Result update(@RequestBody UserInfo userInfo){


        System.out.println(userInfo);
        boolean success = userService.updateById(userInfo);
        if (success){
            return Result.ok();
        }
        return Result.fail();
    }

    // ====================测试接口，不对外开放========================================
    @ApiOperation("仅用作测试重置上报状态")
    @GetMapping("/testReSet")
    public void reSet(){
        userService.reSetReportStatus();
    }


    // =======================KiraYous添加的内容=====================================
    @ApiOperation("添加权限操作")
    @PutMapping("/addPermission")
    @Transactional
    public Result addPermission(@RequestBody PermissionRolesVo permissionRolesVo)
    {

        System.out.println(permissionRolesVo);
        Permission permission=new Permission();
        permission.setPermName(permissionRolesVo.getPermName());
        permission.setPermTag(permissionRolesVo.getPermTag());
        permission.setUrl(permissionRolesVo.getPermUrl());
        permission.setPermId(permissionRolesVo.getPermId());
        int permissionId=permissionMapper.insert(permission);
        if (permissionId==-1) return Result.fail().message("添加权限失败");
        permissionId=permission.getPermId();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("role_name",permissionRolesVo.getRoles());
        Role res=roleService.getOne(queryWrapper);
        if (res==null) return Result.fail().message("当前角色不存在");
        RolePermission rolePermission=new RolePermission();
        rolePermission.setPermId(permissionId);
        rolePermission.setRoleId(res.getRoleId());
        boolean resRole=rolePermissionService.save(rolePermission);
        if (resRole==false)return Result.fail().message("添加权限失败");
        return Result.ok().message("权限成功！").code(ResultCodeEnum.SUCCESS);
    }
    @ApiOperation("获取权限操作")
    @Transactional
    @GetMapping("/getPermission")
    public Result getPermission(@RequestParam(value = "current",defaultValue = "1") Integer current,@RequestParam(value = "limit",defaultValue = "5")Integer limit,@RequestParam(required = false)Map<String,String> searchObj){




        try {
            Page<PermissionRolesUserVo> page=new Page<>(current,limit);


            QueryWrapper<PermissionRolesUserVo> queryWrapper=new QueryWrapper();


            System.out.println(searchObj);
            String temp=searchObj.get("searchObj");

            JSONObject jsonObject = JSON.parseObject(temp);
            String username=jsonObject.getString("username");
            String roles=jsonObject.getString("roles");


            System.out.println(username);
            System.out.println(roles);
            if (username!=null)queryWrapper.eq("q.username",username);
            if (roles!=null)queryWrapper.eq("q.role_name",roles);

            IPage<PermissionRolesUserVo> iPage=permissionMapper.selectPermissionRolesUserVo(page,queryWrapper);

            List<PermissionRolesUserVo> list=iPage.getRecords();
            long currentReturn=iPage.getCurrent();
            long totalReturn =iPage.getTotal();
            Map<String,Object> tempMap=new HashMap<>();
            tempMap.put("current",currentReturn);
            tempMap.put("total",totalReturn);
            tempMap.put("list",list);
            return Result.ok().data(tempMap);

        }catch (Exception e)
        {
            return Result.fail().message("获取权限失败！");
        }






    }

}

